package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"usered/models"
)

type UseredController struct {
	beego.Controller
}
type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UseredController) Add() {
	name := c.GetString("name")
	score := c.GetString("score")
	wei := c.GetString("wei")
	ri := c.GetString("ri")
	zt := c.GetString("zt")

	var usered = models.Userrd{
		Name:  name,
		Score: score,
		Wei:   wei,
		Ri:    ri,
		Zt:    zt,
	}
	err := models.DB.Create(&usered).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "添加失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "添加成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *UseredController) List() {
	var user = models.Userrd{}
	err := models.DB.Find(&user).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: user,
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *UseredController) Up() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	score := c.GetString("score")
	wei := c.GetString("wei")
	ri := c.GetString("ri")
	zt := c.GetString("zt")

	var usered = models.Userrd{
		Id:    id,
		Name:  name,
		Score: score,
		Wei:   wei,
		Ri:    ri,
		Zt:    zt,
	}
	err := models.DB.Save(&usered).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "修改失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "修改成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
func (c *UseredController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&UseredController{}, id).Error
	if err != nil {
		res := JsonR{
			Code: 0,
			Msg:  "删除失败",
		}
		c.Data["json"] = res
		c.ServeJSON()
	} else {
		res := JsonR{
			Code: 200,
			Msg:  "删除成功",
		}
		c.Data["json"] = res
		c.ServeJSON()
	}
}
